import { defineStore } from 'pinia'
import { reactive, ref } from 'vue'
import type { Song, PlayableSong } from '@/assets/apis/MusicDataType'

// 添加歌曲到播放列表，过滤重复的歌曲
function concatPlays(newList: Song[] = [], oldList: Song[] = []) {
  const arr = [...oldList, ...newList]
  const map = new Map()
  for (const item of arr) {
    if (!map.has(item.id)) {
      map.set(item.id, item)
    }
  }
  return [...map.values()]
}

// 当前歌曲在播放列表的索引
const findIndex = (song: Song, playList: Song[]) => {
  return playList.findIndex(d => {
    return d.id === song.id
  })
}

export const usePlayStore = defineStore('playStore', () => {
    const playList = reactive<PlayableSong[]>([])
    const playIndex = ref(0)
    const isPlayed = ref(false)
    const isShowPlayListTips = ref(false)
    const playListId = ref(0)  //歌单id
    const currentSong = ref<PlayableSong | null>(null)

    // 播放歌曲列表里全部歌曲（清空当前播放列表）
    const playAll = (list: Song[]) => {
      if (!Array.isArray(list)) {
        console.error('playAll: 传入的参数必须是数组')
        return
      }
      playList.splice(0, playList.length, ...list)
      playIndex.value = 0
      isPlayed.value = true
    }

    // 播放当前选中的歌曲
    const selectPlay = (list: PlayableSong[]) => {
      if (!Array.isArray(list) || list.length === 0) {
        console.error('selectPlay: 传入的参数必须是非空数组')
        return
      }
      playListId.value=0
      playList.splice(0, playList.length, ...concatPlays(list, playList))
      console.log('当前播放清单', playList)
      isPlayed.value = true
      playIndex.value = findIndex(list[0], playList)
      currentSong.value = list[0]
    }

    // 添加歌曲到当前播放列表
    const addList = (list: Song[]) => {
      if (!Array.isArray(list)) {
        console.error('addList: 传入的参数必须是数组')
        return
      }
      playList.splice(0, playList.length, ...concatPlays(list, playList))
      isShowPlayListTips.value = true
      playListId.value=0
    }
    //从播放列表删除指定索引歌曲
    const deSong = (index) => {
      if (playList.length > 1) {
        playList.splice(index, 1);
      } else {
        isPlayed.value = false;
      }
    }

    return { playList, playIndex, isPlayed, isShowPlayListTips, playListId, playAll, selectPlay, addList, deSong, currentSong }
  },
  {
    //开启持久化 = 》 localStorage
    persist: {
      key: 'playStore',
      storage: localStorage,
      pick: ['playList', 'playIndex']
    }
  }
)
